import Vue from 'vue'
// 只能输入正整数
Vue.directive('enterNumber', {
  inserted: function (el) {
    el.addEventListener("keypress", function (e) {
      e = e || window.event;
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if (charcode == 45) {
        if (el.value.includes('-')) {
          e.preventDefault();
        }
        return;
      } else if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });
  }
});
// 只能输入正数(包含小数)
Vue.directive('enterNumber2', {
  inserted: function (el) {
    el.addEventListener("keypress", function (e) {
      e = e || window.event;
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if (charcode == 46 || charcode == 45) {
        if (el.value.includes('.') || el.value.includes('-')) {
          e.preventDefault();
        }
        return;
      } else if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });
  }
})
//只能输入 >0
Vue.directive('enterNumber3', {
  inserted: function (el) {
    el.addEventListener("keypress", function (e) {
      e = e || window.event;
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      let re = /\d/;

      if (charcode == 48 || charcode == 45) {
        e.preventDefault();
        return;
      }
      else if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && charcode < 1 && !e.ctrlKey) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
    });
  }
});
//只能输入 1和0
// Vue.directive('enterNumber4', {
//   inserted: function (el) {
//     el.addEventListener("keypress", function (e) {
//       e = e || window.event;
//       let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
//       let re = /\d/;

//       if (charcode > 49 || charcode < 48) {
//         if (e.preventDefault) {
//           e.preventDefault();
//         } else {
//           e.returnValue = false;
//         }
//       }
//     });
//   }
// });


//下拉框上拉加载
Vue.directive('el-select-loadmore', {
  bind (el, binding) {
    const selectWrap = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
    selectWrap.addEventListener('scroll', function () {
      const scrollDistance = this.scrollHeight - this.scrollTop <= this.clientHeight;
      if (scrollDistance) {
        binding.value();
      }
    });
  }
})

// v-dialogDrag: 弹窗拖拽
Vue.directive('dialogDrag', {
  bind (el, binding, vnode, oldVnode) {
    const dialogHeaderEl = el.querySelector('.el-dialog__header');
    const dragDom = el.querySelector('.el-dialog');
    dragDom.style.top = "0px";
    dragDom.style.left = "0px";
    dialogHeaderEl.style.cursor = 'move';
    const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
    //拖拽的代码
    dialogHeaderEl.onmousedown = (e) => {
      var e = event || window.event;//兼容
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft;
      const disY = e.clientY - dialogHeaderEl.offsetTop;
      const dragDomWidth = dragDom.offsetWidth; // 对话框宽度
      const dragDomheight = dragDom.offsetHeight; // 对话框高度
      const screenWidth = document.body.clientWidth; // body当前宽度
      const screenHeight = document.documentElement.clientHeight;
      const minDragDomLeft = dragDom.offsetLeft;
      const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;
      const minDragDomTop = dragDom.offsetTop;
      const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;
      // 获取到的值带px 正则匹配替换
      let styL, styT;
      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (sty.left.includes('%')) {
        styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
        styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
      } else {
        styL = +sty.left.replace(/\px/g, '');
        styT = +sty.top.replace(/\px/g, '');
      };
      document.onmousemove = function (e) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
        // 通过事件委托，计算移动的距离
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        //边界处理
        if (-(left) > minDragDomLeft) {
          left = -(minDragDomLeft);
        }
        else if (left > maxDragDomLeft) {
          left = maxDragDomLeft;
        }
        if (-(top) > minDragDomTop) {
          top = -(minDragDomTop);
        }
        else if (top > maxDragDomTop) {
          top = maxDragDomTop;
        }
        // 移动当前元素 
        dragDom.style.left = `${left + styL}px`;
        dragDom.style.top = `${top + styT}px`;
        //将此时的位置传出去
        // binding.value({x:e.pageX,y:e.pageY})
      };
      document.onmouseup = function (e) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  }
})


// 设置样式
function setStyle ($tr, finallIndex, callback1, callback2) { // callback1:默认样式设置,callback2:拖动的时候样式
  for (let tri = 0; tri < $tr.length; tri++) { // 遍历tr,将th和td放到最终的位置上
    const itemtr = $tr[tri];
    if (itemtr.getElementsByTagName('th').length) {
      const $ths = itemtr.getElementsByTagName('th');
      for (let thi = 0; thi < $ths.length; thi++) {
        if (callback1) { callback1($ths[thi]) }
      }
      if (callback2) { callback2($ths[finallIndex]) }
    }
    if (itemtr.getElementsByTagName('td').length) {
      const $tds = itemtr.getElementsByTagName('td');
      for (let tdi = 0; tdi < $tds.length; tdi++) {
        if (callback1) { callback1($tds[tdi]) }
      }
      if (callback2) { callback2($tds[finallIndex]) }
    }
  }
}
// 自定义指令
Vue.directive("slldrag", {
  bind: (el, binding) => {
    let op = el;  //获取当前元素
    op.onmousedown = (e) => {
      //算出鼠标相对元素的位置
      let disX = e.clientX - op.offsetLeft;
      let disY = e.clientY - op.offsetTop;
      let dragTable = null
      if (e.path[4].getAttribute('id')) {
        dragTable = e.path[4].getAttribute('id')
      } else {
        dragTable = e.path[5].getAttribute('id')
      }
      let thWidthArr = []; // 记录所有的th的宽度,依次累加
      let finallIndex = 0;//最终的th index
      let directionIndex = 0; // 单击的是第几个th
      let $insertTh = null;

      $insertTh = e.target;

      const $th = op.parentNode.children; // 获取所有th
      for (let thi = 0; thi < $th.length; thi++) {
        const itemth = $th[thi];
        itemth.index = thi;
        let offsetWidth = 0;
        if (thi === 0) {
          offsetWidth = itemth.offsetWidth + offsetWidth; // 如果是第一个th就不进行累加操作
        } else {
          offsetWidth = itemth.offsetWidth + thWidthArr[thi - 1]; // 累加th的宽度
        }
        thWidthArr.push(offsetWidth)
      }
      directionIndex = e.target.index;

      // 以鼠标按下的这个th处,创建一个和th内容一样的div,
      const $createDiv = document.createElement('div');
      $createDiv.id = 'created-div';
      document.getElementById(dragTable).appendChild($createDiv);

      document.onmousemove = (e) => {
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        if (Math.abs(e.clientX - disX - op.offsetLeft) < 10) { return; }
        //绑定元素位置到positionX和positionY上面
        // this.positionX = top;
        // this.positionY = left;

        //移动当前元素
        const thText = op.innerHTML;
        $createDiv.innerHTML = thText;
        $createDiv.style.position = 'absolute';
        $createDiv.style.width = op.offsetWidth + 'px';
        $createDiv.style.height = op.offsetHeight + 'px';
        $createDiv.style.background = '#fafafa';
        $createDiv.style.left = left + 'px';
        $createDiv.style.top = top + 'px';

        finallIndex = 0; //鼠标拖动过程中所停留在的th的index
        if (left <= 0) { // // 小于0的时候就等于0
          finallIndex = 0;
        } else if (left > thWidthArr[thWidthArr.length - 1]) { // 大于最后一个的时候就最后一个+1
          finallIndex = thWidthArr.length;
        } else {
          for (let i = 0; i < thWidthArr.length; i++) {
            if (left >= thWidthArr[i - 1] && left <= thWidthArr[i]) {
              finallIndex = i;
            }
          }
        }

        // 拖动的时候用红线标识拖动到哪个位置
        const $tr = document.getElementById(dragTable).getElementsByTagName('table')[0].getElementsByTagName('tr');

        document.getElementById(dragTable).style.userSelect = 'none'  // 禁止选取文本

        // 拖动的时候设置表格的样式
        if (finallIndex === thWidthArr.length) {
          // 如果是最后一个表格就设置右侧的边框
          setStyle($tr, (finallIndex - 1), (dom) => {
            dom.style.borderColor = '1px solid #dedfe3';
          }, (dom) => {
            dom.style.borderRight = '1px solid #CCC1DB';
          });
        } else {
          // 如果不是最后一列表格就设置左侧的边框
          setStyle($tr, finallIndex, (dom) => {
            dom.style.borderColor = '1px solid #dedfe3';
          }, (dom) => {
            dom.style.borderLeft = '1px solid #CCC1DB';
          });
        }

      };
      document.onmouseup = (e) => {
        const $tr = document.getElementById(dragTable).getElementsByTagName('table')[0].getElementsByTagName('tr');
        document.getElementById(dragTable).removeChild($createDiv);

        document.getElementById(dragTable).style.userSelect = 'text'  // 可以选取文本

        // 鼠标抬起恢复表格的样式
        let _finallIndex = finallIndex === thWidthArr.length ? _finallIndex = finallIndex - 1 : finallIndex; // 如果是拖动到最后一个th
        setStyle($tr, _finallIndex, (dom) => {
          dom.style.borderLeft = '1px solid #dedfe3'
          dom.style.borderRight = '1px solid #dedfe3'
        }, (dom) => {
          dom.style.borderLeft = '1px solid #dedfe3'
          dom.style.borderRight = '1px solid #dedfe3'
        });
        // 取消鼠标拖动和鼠标抬起事件
        document.onmousemove = null;
        document.onmouseup = null;

        // 如果没有进行拖动操作(鼠标点下就抬起)
        if (Math.abs(e.clientX - disX - op.offsetLeft) < 10) {
          thWidthArr = []; disX = 0;
          return;
        }

        // 遍历tr,将th和td放到最终的位置上
        for (let tri = 0; tri < $tr.length; tri++) {
          const itemtr = $tr[tri];
          if (itemtr.getElementsByTagName('th').length) {
            const $ths = itemtr.getElementsByTagName('th');
            itemtr.insertBefore($insertTh, $ths[finallIndex]);
          }
          if (itemtr.getElementsByTagName('td').length) {
            const $tds = itemtr.getElementsByTagName('td');
            itemtr.insertBefore($tds[directionIndex], $tds[finallIndex]);

          }
        }

        // 重置thWidthArr和disX
        thWidthArr = []; disX = 0;
      };
    };
  }
});


